<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="680"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改用户' : '新建用户'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-row :gutter="16">
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入姓名"
              v-model:value="form.name"
              @blur="validate('name', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="账号" v-bind="validateInfos.account">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入姓名"
              v-model:value="form.account"
              @blur="validate('account', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="密码" v-bind="validateInfos.password">
            <a-input-password
              allow-clear
              :maxlength="20"
              placeholder="请输入姓名"
              v-model:value="form.password"
              @blur="validate('password', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="年龄" v-bind="validateInfos.age">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入年龄"
              v-model:value="form.age"
              @blur="validate('age', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="性别" v-bind="validateInfos.sex">
            <a-select
              v-model:value="form.sex"
              placeholder="请选择性别"
              allow-clear
            >
              <a-select-option value="男">男</a-select-option>
              <a-select-option value="女">女</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="在职状态" v-bind="validateInfos.work_status">
            <a-select
              v-model:value="form.work_status"
              placeholder="请选择在职状态"
              allow-clear
            >
              <a-select-option value="0">试用</a-select-option>
              <a-select-option value="1">正式</a-select-option>
              <a-select-option value="2">离职</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="主角色" v-bind="validateInfos.main_role">
            <role-select
              v-model:value="form.main_role"
              @blur="validate('main_role', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="其他角色" v-bind="validateInfos.other_roles">
            <otherRole-select
              v-model:value="form.other_roles"
              @blur="
                validate('other_roles', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="生日日期">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择生日日期"
              v-model:value="birthday"
            />
          </a-form-item>
          <a-form-item label="入职日期">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择入职日期"
              v-model:value="employment_data"
            />
          </a-form-item>
          <a-form-item label="转正时间">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择转正时间"
              v-model:value="formal_date"
            />
          </a-form-item>
          <a-form-item label="离职时间">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择离职时间"
              v-model:value="leave_date"
            />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24" :xs="24">
          <a-form-item label="手机号" v-bind="validateInfos.mobile">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入手机号"
              v-model:value="form.mobile"
              @blur="validate('mobile', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="qq" v-bind="validateInfos.qq">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入QQ"
              v-model:value="form.qq"
              @blur="validate('qq', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="email" v-bind="validateInfos.email">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入email"
              v-model:value="form.email"
              @blur="validate('email', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="紧急联系人" v-bind="validateInfos.contact_name">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入紧急联系人"
              v-model:value="form.contact_name"
              @blur="
                validate('contact_name', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="紧急电话" v-bind="validateInfos.contact_mobile">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入紧急联系人电话"
              v-model:value="form.contact_mobile"
              @blur="
                validate('contact_mobile', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="身份证号" v-bind="validateInfos.id_card">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入身份证号"
              v-model:value="form.id_card"
              @blur="validate('id_card', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="身份证地址" v-bind="validateInfos.id_address">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入身份证地址"
              v-model:value="form.id_address"
              @blur="
                validate('id_address', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item
            label="户口所在地"
            v-bind="validateInfos.residence_address"
          >
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入户口所在地"
              v-model:value="form.residence_address"
              @blur="
                validate('residence_address', { trigger: 'blur' }).catch(
                  () => {}
                )
              "
            />
          </a-form-item>
          <a-form-item label="现居住地" v-bind="validateInfos.live_address">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入现居住地"
              v-model:value="form.live_address"
              @blur="
                validate('live_address', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { emailReg, phoneReg } from 'ele-admin-pro';
  import RoleSelect from './role-select.vue';
  import OtherRoleSelect from './otherRole-select.vue';
  import { addUser, updateUser } from '@/api/user/user';
  import dayjs from 'dayjs';

  const useForm = Form.useForm;

  const emit = defineEmits(['done', 'update:visible']);

  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  });

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const form = reactive({
    id: '',
    user_id: '',
    name: '',
    account: '',
    password: '',
    age: '',
    sex: [],
    work_status: [],
    main_role: undefined,
    other_roles: [],
    birthday: '',
    employment_data: '',
    formal_date: '',
    leave_date: '',
    mobile: '',
    qq: '',
    email: '',
    contact_name: '',
    contact_mobile: '',
    id_card: '',
    id_address: '',
    residence_address: '',
    live_address: ''
  });
  // 出生日期
  const birthday = ref();
  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入用户名',
        type: 'string',
        trigger: 'blur'
      }
    ],
    account: [
      {
        required: true,
        message: '请输入账号',
        type: 'string',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        type: 'string',
        trigger: 'blur',
        validator: async (_rule, value) => {
          if (isUpdate.value || /^[\S]{5,18}$/.test(value)) {
            return Promise.resolve();
          }
          return Promise.reject('密码必须为5-18位非空白字符');
        }
      }
    ],
    age: [
      {
        required: true,
        message: '请输入年龄',
        type: 'string',
        trigger: 'blur'
      }
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
        type: 'string',
        trigger: 'blur'
      }
    ],
    work_status: [
      {
        required: true,
        message: '请选择在职状态',
        type: 'string',
        trigger: 'blur'
      }
    ],
    main_role: [
      {
        required: true,
        message: '请选择主角色',
        type: 'string',
        trigger: 'blur'
      }
    ],
    other_roles: [
      {
        required: true,
        message: '请选择其他角色',
        type: 'string',
        trigger: 'blur'
      }
    ],
    roles: [
      {
        required: true,
        message: '请选择角色',
        type: 'array',
        trigger: 'blur'
      }
    ],
    mobile: [
      {
        required: true,
        pattern: phoneReg,
        message: '手机号格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ],
    email: [
      {
        required: true,
        pattern: emailReg,
        message: '邮箱格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ],
    contact_name: [
      {
        required: true,
        message: '请输入紧急联系人',
        type: 'string',
        trigger: 'blur'
      }
    ],
    contact_mobile: [
      {
        required: true,
        message: '请输入紧急联系人电话',
        type: 'string',
        trigger: 'blur'
      }
    ],
    id_card: [
      {
        required: true,
        message: '请输入身份证号',
        type: 'string',
        trigger: 'blur'
      }
    ],
    id_address: [
      {
        required: true,
        message: '请输入身份证地址',
        type: 'string',
        trigger: 'blur'
      }
    ],
    residence_address: [
      {
        required: true,
        message: '请输入户口所在地',
        type: 'string',
        trigger: 'blur'
      }
    ],
    live_address: [
      {
        required: true,
        message: '请输入现居住地',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const { resetFields, validate, validateInfos } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        const data = {
          ...form,
          birthday: birthday.value?.format('YYYY-MM-DD'),
          employment_data: birthday.value?.format('YYYY-MM-DD'),
          formal_date: birthday.value?.format('YYYY-MM-DD'),
          leave_date: birthday.value?.format('YYYY-MM-DD')
        };
        console.log(data);
        const saveOrUpdate = isUpdate.value ? updateUser : addUser;
        saveOrUpdate(data)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          const info = props.data.info;
          assignObject(form, props.data);
          assignObject(form, info);
          console.log(form);
          if (props.data.birthday) {
            birthday.value = dayjs(props.data.birthday, 'YYYY-MM-DD');
          } else {
            birthday.value = undefined;
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        birthday.value = undefined;
      }
    }
  );
</script>
